
$(document).ready(function () {

    $("#account_user_type").change(onUserTypeChange);
    $("#btn_add_user").click(function () {
        if (accountList.accounts.length >= 40) {
            UIkit.notify("一次最多添加 40 个用户，请先提交后，再继续添加。", {status: "warning"});
            return;
        }
        openAccountInfoDialog();
    });
    AccountInfoDialog.addSaveButtonClickHandler(onNewAccountSave);
    $("#btn_remove_user").click(function () {
        if ($('.selected-table-row').length < 1) {
            UIkit.notify("请选择至少一个用户。", {status: "warning"});
            return;
        }
        UIkit.modal.confirm("确定删除选中的用户？", onAccountsRemove);
    });
    $("#btn_submit_all").click(function () {
        if ($('#tbody_account_list>tr').length < 1) {
            UIkit.notify("没有需要创建的用户。", {status: "warning"});
            return;
        }
        UIkit.modal.confirm("确定提交所有用户？", onAccountsSubmit);
    });
    $(".check-box").click(onCheckBoxClick);


    $.validator.setDefaults({
        errorClass: "uk-text-danger",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass("uk-form-danger");
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass("uk-form-danger");
        }
    });
    AccountInfoDialog.setupFormValidation();
    onUserTypeChange();
});

function openAccountInfoDialog() {
    AccountInfoDialog.resetAccountInfoDialog();
    if ($(this).is('a')) {
        var index = parseInt($(this).parent().prevAll()[3].textContent) - 1;
        var account = accountList.accounts[index];
        if (account == null) {
            UIkit.notify("无法查看该账号。", {status: 'danger'});
            return;
        } else {
            $('#account_index')[0].value = index;
            AccountInfoDialog.fillUpForms(account);
        }
    }
    onUserTypeChange();
    UIkit.modal('#dialog').show();
}

function onUserTypeChange() {
    var selectedOption = $('#account_user_type option:selected')[0];
    AccountInfoDialog.changeUserType(selectedOption.value);
}

function onCheckBoxClick() {
    if ($(this).is(':checked')) {
        $(this).parent().parent().addClass('selected-table-row');
    } else {
        $(this).parent().parent().removeClass('selected-table-row');
    }
}

function accountToTableRow(account, index) {
    var username = null;
    var userType = null;
    var name = null;
    if (account.student != null) {
        username = account.student.studentNumber;
        userType = "学生";
        name = account.student.name;
    } else {
        username = account.teacher.teacherNumber;
        userType = "教师";
        name = account.teacher.name;
    }

    var a = $("<a>查看</a>");
    a.click(openAccountInfoDialog);
    var detailTableCell = $("<td></td>").append(a);
    var checkBoxTableCell = $("<td style=\"vertical-align: middle\"></td>");
    var checkBox = $("<input type=\"checkbox\" class=\"check-box\">");
    checkBox.click(onCheckBoxClick);
    checkBoxTableCell.append(checkBox);
    var tableRow = $("<tr></tr>")
        .append($("<td class=\"index-table-cell\">" + index + "</td>"))
        .append("<td>" + username + "</td>")
        .append("<td>" + userType + "</td>")
        .append("<td>" + name + "</td>")
        .append(detailTableCell)
        .append(checkBoxTableCell);
    return tableRow
}

function onNewAccountSave() {
    var userType = $('#account_user_type')[0].value;
    var isValid = false;
    var account = null;
    var form = null;
    var index = parseInt($('#account_index')[0].value);

    if (userType === "S") {
        form = $('#form_student_info');
        isValid = form.valid();

        if (isValid) {
            var student = form.serializeJSON({skipFalsyValuesForTypes: ['string', 'number']});
            account = {
                student: student,
                userType: userType
            };
        }
    } else if (userType === "T") {
        form = $('#form_teacher_info');
        isValid = form.valid();

        if (isValid) {
            var teacher = form.serializeJSON({skipFalsyValuesForTypes: ['string', 'number']});
            account = {
                teacher: teacher,
                userType: userType
            }
        }
    }

    if (!isValid) {
        return;
    }


    if (account != null) {
        if (isNaN(index))
            accountList.add(account);
        else {
            accountList.replace(account, index);
        }
    }

    UIkit.modal('#dialog').hide();
}

function onAccountsRemove() {
    $(".selected-table-row").each(function () {
        var index = parseInt($(this).find("td:first-child").text());
        accountList.remove(index - 1);
    });
}

var blockingModal;
function onAccountsSubmit() {
    blockingModal = UIkit.modal.blockUI("正在提交...");
    $.ajax({
        url: '/api/admin/add_accounts',
        type: 'POST',
        data: JSON.stringify(accountList.accounts),
        contentType: "application/json"
    })
        .done(function (data) {
            UIkit.modal.blockUI("提交成功！3 秒后将刷新页面。");
            setTimeout(function (args) { window.location.reload(true) }, 3000);
        })
        .fail(function (jqXHR) {
            try {
                var response = JSON.parse(jqXHR.responseText);
                if (response != null && response.error != null) {
                    UIkit.modal.alert("发生错误: " + response.error.message);
                } else {
                    UIkit.modal.alert("发生错误。")
                }
            } catch (e) {
                UIkit.modal.alert("发生错误。");
                console.error(e);
            }
        })
        .always(function () {
            blockingModal.hide();
        })
}